package com.fiberhome.nas.feature.photo.view

import android.app.Activity
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import com.fiberhome.nas.core.designsystem.component.SpaceBetweenRow
import com.fiberhome.nas.core.designsystem.theme.AppTheme
import com.fiberhome.nas.core.designsystem.theme.ArrowLeftIcon
import com.fiberhome.nas.core.designsystem.theme.BgGreyLight
import com.fiberhome.nas.core.designsystem.theme.BodyLarge
import com.fiberhome.nas.core.designsystem.theme.Primary
import com.fiberhome.nas.core.designsystem.theme.ShapeSmall
import com.fiberhome.nas.core.designsystem.theme.SpaceHorizontalLarge
import com.fiberhome.nas.core.designsystem.theme.SpaceHorizontalSmall
import com.fiberhome.nas.core.designsystem.theme.SpacePaddingLarge
import com.fiberhome.nas.core.designsystem.theme.SpacePaddingSmall
import com.fiberhome.nas.core.designsystem.theme.SpaceVerticalSmall
import com.fiberhome.nas.core.designsystem.theme.SpaceVerticalXSmall
import com.fiberhome.nas.core.designsystem.theme.TextSecondaryLight
import com.fiberhome.nas.core.designsystem.theme.TitleLarge
import com.fiberhome.nas.core.model.entity.AlbumInfo
import com.fiberhome.nas.core.model.entity.LocalAlbum
import com.fiberhome.nas.core.model.entity.LocalMediaItem
import com.fiberhome.nas.core.ui.component.image.CheckImage
import com.fiberhome.nas.core.ui.component.image.LocalPhotoImage
import com.fiberhome.nas.core.ui.component.scaffold.AppScaffold
import com.fiberhome.nas.core.ui.component.text.AppText
import com.fiberhome.nas.core.ui.component.text.TextType
import com.fiberhome.nas.core.util.permission.PermissionUtils
import com.fiberhome.nas.core.util.time.formatToDate
import com.fiberhome.nas.core.util.toast.ToastUtils
import com.fiberhome.nas.feature.common.ext.photoGridDragHandler
import com.fiberhome.nas.feature.photo.viewmodel.PhotoUploadViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive

@Composable
internal fun PhotoUploadRoute(
    viewModel: PhotoUploadViewModel = hiltViewModel(),
) {
    val context = LocalContext.current
    val photos by viewModel.photos.collectAsState()
    val localAlbums by viewModel.localAlbums.collectAsState()
    val selectedIds by viewModel.selectedIds.collectAsState()
    val deviceAlbums by viewModel.deviceAlbums.collectAsState()
    var hasPermission by remember { mutableStateOf(false) }

    // 检查相册权限
    LaunchedEffect(Unit) {
        if (context is Activity) {
            PermissionUtils.requestGalleryPermission(context) { granted ->
                hasPermission = granted
                if (granted) {
                    viewModel.initData()
                } else {
                    ToastUtils.showError("相册权限获取失败")
                }
            }
        } else {
            viewModel.initData()
        }
    }

//    AiPhotoAlbumScreen()
    if (hasPermission && localAlbums.isNotEmpty()) {
        PhotoUploadScreen(
            photos = photos,
            localAlbums = localAlbums,
            deviceAlbums = deviceAlbums,
            selectedIds = selectedIds,
            onBackClick = viewModel::navigateBack,
            onClearSelection = viewModel::clearSelectedItems,
            toggleSelectAll = viewModel::toggleSelectAll,
            onToggleItemsSelection = viewModel::toggleItemsSelection,
            onUploadSelectedPhotos = viewModel::uploadSelectedPhotos,
            onSelectLocalAlbum = viewModel::onSelectLocalAlbum
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PhotoUploadScreen(
    photos: List<LocalMediaItem>,
    localAlbums: List<LocalAlbum>,
    deviceAlbums: List<AlbumInfo>,
    selectedIds: Set<Long>,
    onBackClick: () -> Unit,
    onClearSelection: () -> Unit = {},
    toggleSelectAll: (Boolean) -> Unit = {},
    onToggleItemsSelection: (List<Long>, Boolean) -> Unit = { _, _ -> },
    onUploadSelectedPhotos: (AlbumInfo) -> Unit = {},
    onSelectLocalAlbum: (LocalAlbum) -> Unit = {},
) {
    // 当前本地相册
    var currentLocalAlbum by remember { mutableStateOf(localAlbums[0]) }
    // 本地相册下拉框展开
    var isAlbumDropdownExpanded by remember { mutableStateOf(false) }
    val selectedIdsState: MutableState<Set<Long>> = rememberSaveable { mutableStateOf(emptySet()) }
    // 仅显示未备份照片
    var showUnbackedUpOnly by remember { mutableStateOf(false) }
    // 声明共享的滚动状态
    val gridState = rememberLazyGridState()
    val autoScrollSpeed = remember { mutableStateOf(0f) }

    // 根据筛选条件过滤照片
    val displayPhotos = photos
        .filter { if (showUnbackedUpOnly) it.isUnbackedUp() else true }
        .groupBy { it.dateTaken.formatToDate() }

    //滑动监听
    LaunchedEffect(autoScrollSpeed.value) {
        if (autoScrollSpeed.value != 0f) {
            while (isActive) {
                gridState.scrollBy(autoScrollSpeed.value)
                delay(10)
            }
        }
    }
    LaunchedEffect(selectedIds) {
        selectedIdsState.value = selectedIds
    }

    AppScaffold(
        topBar = {
            CenterAlignedTopAppBar(
                title = {
                    TextButton(
                        onClick = { isAlbumDropdownExpanded = true }) {
                        AppText(
                            text = currentLocalAlbum.albumName,
                            style = TitleLarge,
                            color = MaterialTheme.colorScheme.onSurface,
                        )
                        Icon(
                            imageVector =
                                if (isAlbumDropdownExpanded) Icons.Default.KeyboardArrowUp
                                else Icons.Default.KeyboardArrowDown,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.onSurface
                        )
                    }

                    DropdownMenu(
                        modifier = Modifier
                            .width(200.dp)
                            .heightIn(max = 300.dp), // 限制最大高度
                        expanded = isAlbumDropdownExpanded,
                        onDismissRequest = { isAlbumDropdownExpanded = false }) {
                        localAlbums.forEach { album ->
                            DropdownMenuItem(
                                text = {
                                    AppText(
                                        text = "${album.albumName} (${album.getTotalCount()})",
                                        style = BodyLarge,
                                    )
                                },
                                onClick = {
                                    currentLocalAlbum = album
                                    isAlbumDropdownExpanded = false
                                    onSelectLocalAlbum(currentLocalAlbum)
                                    onClearSelection()
                                },
                                leadingIcon = {
                                    AsyncImage(
                                        model = album.coverUri,
                                        contentDescription = album.albumName,
                                        contentScale = ContentScale.Crop,
                                        modifier = Modifier
                                            .size(40.dp)
                                            .clip(ShapeSmall)
                                    )
                                },
                            )
                        }
                    }
                },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        ArrowLeftIcon()
                    }
                },
                actions = {
                    val selectAll = selectedIdsState.value.size == displayPhotos.size
                    AppText(
                        modifier = Modifier.padding(end = SpacePaddingLarge),
                        text = if (selectAll) "取消全选" else "全选",
                        style = TitleLarge,
                        onClick = {
                            toggleSelectAll(!selectAll)
                        })
                }
            )
        }
    ) {
        Column(modifier = Modifier.fillMaxSize()) {
            Card(Modifier.padding(SpacePaddingLarge)) {
                SpaceBetweenRow(Modifier.padding(horizontal = SpaceHorizontalSmall)) {
                    AppText(text = "仅显示未备份的照片", style = BodyLarge)
                    Switch(
                        checked = showUnbackedUpOnly,
                        onCheckedChange = {
                            showUnbackedUpOnly = it
                            onClearSelection()
                        }
                    )
                }
            }

            Box {
                LazyVerticalGrid(
                    state = gridState,
                    columns = GridCells.Fixed(4),
                    modifier = Modifier
                        .fillMaxSize()
                        .photoGridDragHandler(  //手势滑动选中
                            lazyGridState = gridState,
                            haptics = LocalHapticFeedback.current,
                            selectedIds = selectedIdsState,
                            onSelectionChanged = onToggleItemsSelection,
                            autoScrollSpeed = autoScrollSpeed,
                            autoScrollThreshold = with(LocalDensity.current) { 40.dp.toPx() }),
                    horizontalArrangement = Arrangement.spacedBy(SpaceHorizontalSmall),
                    verticalArrangement = Arrangement.spacedBy(SpaceVerticalSmall),
                    contentPadding = PaddingValues(
                        SpacePaddingLarge, SpacePaddingLarge, SpacePaddingLarge, 100.dp
                    ),
                ) {
                    //内容
                    displayPhotos.forEach { (date, photos) ->
                        // 日期标题
                        item(span = { GridItemSpan(4) }) {
                            SpaceBetweenRow {
                                Text(
                                    text = date,
                                    fontSize = 14.sp,
                                    color = TextSecondaryLight,
                                    modifier = Modifier.padding(vertical = 8.dp)
                                )
                                val photoIds = photos.map { it.id }
                                val selected = selectedIds.containsAll(photoIds)
                                CheckImage(
                                    modifier = Modifier.clickable {
                                        onToggleItemsSelection(
                                            photoIds,
                                            !selected
                                        )
                                    },
                                    selected = selected,
                                )
                            }
                        }
                        // 照片网格项
                        items(photos, key = { it.id }) { photo ->
                            val selected = selectedIds.contains(photo.id)
                            LocalPhotoImage(
                                photo = photo,
                                editMode = true,
                                selected = selected,
                                modifier = Modifier.clickable {
                                    onToggleItemsSelection(
                                        listOf(photo.id), !selected
                                    )
                                }
                            )
                        }
                    }
                }

                UploadBottomBar(
                    deviceAlbums,
                    selectedIds,
                    onUploadSelectedPhotos,
                    modifier = Modifier
                        .padding(vertical = 40.dp, horizontal = SpaceHorizontalLarge)
                        .align(Alignment.BottomCenter)
                )
            }
        }
    }
}

/**
 * 上传底部操作栏
 */
@Composable
fun UploadBottomBar(
    deviceAlbums: List<AlbumInfo>,
    selectedIds: Set<Long>,
    onUploadSelectedPhotos: (album: AlbumInfo) -> Unit,
    modifier: Modifier = Modifier,
) {
    var deviceAlbumId by remember { mutableStateOf("1") }

    Card(
        modifier,
        elevation = CardDefaults.cardElevation(2.dp),
    ) {
        SpaceBetweenRow(padding = SpacePaddingSmall) {
            AppText(text = "上传至：")

            TextButton(
                onClick = {
//                    deviceAlbumId = showChooseDeviceAlbumDialog(deviceAlbums)
                },
                enabled = true,
                modifier = Modifier
                    .padding(horizontal = SpaceHorizontalSmall)
                    .clip(ShapeSmall)
                    .background(BgGreyLight)
                    .weight(1f)
                    .height(32.dp),
                contentPadding = PaddingValues(
                    horizontal = SpaceHorizontalLarge, vertical = SpaceVerticalXSmall
                )
            ) {
                // 使用Box包裹AppText，并设置内容左对齐
                Box(modifier = Modifier.fillMaxWidth()) {
                    AppText(
                        text = deviceAlbums.find { it.id == deviceAlbumId }?.albumName ?: "",
                        type = TextType.SECONDARY,
                        modifier = Modifier.align(Alignment.CenterStart) // 强制左对齐
                    )
                }
            }

            TextButton(
                onClick = {
                    onUploadSelectedPhotos(deviceAlbums.find { it.id == deviceAlbumId }
                        ?: deviceAlbums[0])
                },
                enabled = selectedIds.isNotEmpty(),
                modifier = Modifier
                    .clip(ShapeSmall)
                    .background(Primary)
                    .height(32.dp),
                contentPadding = PaddingValues(
                    horizontal = SpaceHorizontalLarge, vertical = SpaceVerticalXSmall
                )
            ) {
                AppText(
                    text = "上传(${selectedIds.size})",
                    type = TextType.WHITE,
                )

            }
        }
    }
}


@Preview(showBackground = true)
@Composable
fun PhotoUploadScreenPreview() {
    AppTheme {
        PhotoUploadScreen(
            emptyList(),
            onUploadSelectedPhotos = { },
            onBackClick = { },
            onClearSelection = { },
            onToggleItemsSelection = { _, _ -> },
            selectedIds = emptySet(),
            localAlbums = emptyList(),
            deviceAlbums = emptyList()
        )
    }
}


